package com.ygxsk.carhome;

import android.app.Application;
import android.content.Context;

import androidx.multidex.MultiDex;

import com.blankj.utilcode.util.PathUtils;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.WhiteToastStyle;
import com.kathline.library.content.ZFileContent;
import com.tencent.mmkv.MMKV;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.utils.CommUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.util.Map;

import xcrash.ICrashCallback;
import xcrash.TombstoneManager;
import xcrash.TombstoneParser;
import xcrash.XCrash;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-05  10:58
 * @Description:APP的总控制
 */
public class CarApplication extends Application {


//    static {
//        //启用矢量图兼容
//        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
//        //设置全局默认配置（优先级最低，会被其他设置覆盖）
//        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
//            @Override
//            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
//                //全局设置（优先级最低）
//                layout.setEnableAutoLoadMore(true);
//                layout.setEnableOverScrollDrag(false);
//                layout.setEnableOverScrollBounce(true);
//                layout.setEnableLoadMoreWhenContentNotFull(true);
//                layout.setEnableScrollContentWhenRefreshed(true);
//                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
//                layout.setFooterMaxDragRate(4.0F);
//                layout.setFooterHeight(45);
//            }
//        });
//        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
//            @NonNull
//            @Override
//            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
//                //全局设置主题颜色（优先级第二低，可以覆盖 DefaultRefreshInitializer 的配置，与下面的ClassicsHeader绑定）
//                layout.setEnableHeaderTranslationContent(true);
//                return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s"));
//            }
//        });
//        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
//            @NonNull
//            @Override
//            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
//                return new ClassicsFooter(context);
//            }
//        });
//    }

    private static CarApplication _instance;

    @Override
    public void onCreate() {
        super.onCreate();

        if (_instance == null) {
            _instance = this;
        }

        MMKV.initialize(this);
        //String path = MMKV.initialize(this);
        ///data/user/0/com.ygxsk.integrated/files/mmkv
        //Log.d(ConstantSign.LOGCAT_NOMAL, path);

        Session.get(getApplicationContext());

        //先初始化HTTP的SDK;这个必须放在 _instance 的赋值之后；
        if (MMKV.defaultMMKV().decodeBool(ConstantSign.P_SECRECYTURL_AGREE)) {
            //Log.d(ConstantApi.LOGCAT_NOMAL, "启动APP发现-【已同意】隐私政策");
            CarHelper.methodInitThridSDKWithHTTPInOnCreate(_instance.getApplicationContext());
        }

        ZFileContent.getZFileHelp().init(new MyFileImageListener());

//        SmartCropper.buildImageDetector(this);
        // 初始化吐司工具类
        Toaster.init(this, new WhiteToastStyle());

    }

    public static CarApplication getInstance() {
        return _instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        MultiDex.install(this);

        //添加崩溃日志的回调
        ICrashCallback iCrashCallback = new ICrashCallback() {
            @Override
            public void onCrash(String logPath, String emergency) throws Exception {

                if (emergency != null) {

                    debug(logPath, emergency);

                    // Disk is exhausted, send crash report immediately.
                    sendThenDeleteCrashLog(logPath, emergency);

                } else {

                    // Add some expanded sections. Send crash report at the next time APP startup.

                    // OK
                    TombstoneManager.appendSection(logPath, "expanded_key_1", "expanded_content");
//                    TombstoneManager.appendSection(logPath,"memory info","memory info");
//                    TombstoneManager.appendSection(logPath, "expanded_key_2", "expanded_content_row_1\nexpanded_content_row_2");
                    // Invalid. (Do NOT include multiple consecutive newline characters ("\n\n") in the content string.)
                    // TombstoneManager.appendSection(logPath, "expanded_key_3", "expanded_content_row_1\n\nexpanded_content_row_2");

                    debug(logPath, null);

                    sendThenDeleteCrashLog(logPath, emergency);

                }

            }
        };


        xcrash.XCrash.init(base, new XCrash.InitParameters()
                .setJavaLogCountMax(30)//30个文件
                .setJavaCallback(iCrashCallback)//
                .setNativeCallback(iCrashCallback)//
                .setAnrCallback(iCrashCallback)//
                .setPlaceholderSizeKb(512)//设置占位的控件
                //.setLogDir(PathUtils.getExternalAppFilesPath() + File.separator + "xcrash")//设置路径
                .setLogDir(getExternalFilesDir(ConstantSign.FOLDER_X_CRASH).toString())//设置路径
                .setAnrLogcatSystemLines(0)//系统日志也不打印
                .setJavaLogcatSystemLines(0)//
                .setNativeLogcatSystemLines(0)//
                .setJavaLogcatMainLines(0)//
                .setJavaDumpAllThreads(false)//是否输出所有线程的日志信息
                .setJavaDumpAllThreadsCountMax(0)//输出日志最多的线程数
                .setJavaDumpFds(false)//不输出进程文件描述符
                .setNativeDumpFds(false)//
                .setAnrDumpFds(false)//
                .setNativeDumpAllThreads(false)//
                .setNativeDumpMap(false)//
                .setNativeDumpElfHash(false)//
                .setNativeDumpAllThreadsCountMax(0)//
                .setNativeDumpNetwork(true)//
                .setJavaDumpNetworkInfo(false)//
                .setNativeDumpNetwork(false)//
                .setAnrDumpNetwork(false)//
                .setJavaLogcatEventsLines(0)//
                .setNativeLogcatEventsLines(0)//
                .setNativeLogcatEventsLines(0)//
                .setNativeLogcatMainLines(0)//
                .setNativeRethrow(false)//
                .setAnrCheckProcessState(false)//
                //.disableNativeCrashHandler()
                //.disableAnrCrashHandler()
                .setAnrRethrow(false)//
                .setLogFileMaintainDelayMs(1000)//
        );

    }

    //通用的下载地址信息
    public String getApkDownLoadPath(String _downLoadUrlCurrent) {
        return PathUtils.getInternalAppCachePath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
    }

    private void sendThenDeleteCrashLog(String logPath, String emergency) {

        try {

            //do
            // Parse
            Map<String, String> map = TombstoneParser.parse(logPath, emergency);
            String crashReport = new JSONObject(map).toString();

            //Blob blob = new MySerialBlob(crashReport.getBytes(StandardCharsets.UTF_8));
            // Send the crash report to server-side.
            // ......
            CommUtils.addLog(CarApplication.this.getApplicationContext(),//
                    ConstantSign.INTERFACE_ADDRESS,//xCrash
                    ConstantSign.REQUEST_METHOD_POST,//
                    "xCrash has no requestParam",//
                    crashReport);//

            // If the server-side receives successfully, delete the log file.
            // Note: When you use the placeholder file feature,
            // please always use this method to delete tombstone files.

            //
            TombstoneManager.deleteTombstone(logPath);

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }

    }

    private void debug(String logPath, String emergency) {
        // Parse and save the crash info to a JSON file for debugging.
        FileWriter writer = null;
        try {
            File debug = new File(XCrash.getLogDir() + "/debug.json");
            debug.createNewFile();
            writer = new FileWriter(debug, false);
            writer.write(new JSONObject(TombstoneParser.parse(logPath, emergency)).toString());
        } catch (Exception e) {
//            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "debug failed", e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ignored) {
                }
            }
        }
    }


}
